package com.latsen.pawfit.common.util.glide

import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.signature.ObjectKey

object GlideImageLoader {

    fun load(imageView: ImageView, resource: GlideResource, options: GlideImageOptions? = null) {
        val rm = kotlin.run {
            val fragment = options?.fragment
            val activity = options?.activity
            when {
                fragment != null -> Glide.with(fragment)
                activity != null -> Glide.with(activity)
                else -> Glide.with(imageView)
            }
        }

        val req = kotlin.run {
            val url = resource.url
            val drawable = resource.drawable
            val resId = resource.drawableId
            when {
                url != null -> rm.load(url)
                drawable != null -> rm.load(drawable)
                resId != null -> rm.load(resId)
                else -> throw IllegalArgumentException("Not resource found!")
            }
        }

        if (options == null) {
            req.into(imageView)
            return
        }

        val reqOptions = RequestOptions().apply {
            options.placeHolder?.let {
                val resId = it.drawableId
                val drawable = it.drawable
                when {
                    drawable != null -> placeholder(it.drawable)
                    resId != null -> placeholder(resId)
                    else -> throw IllegalArgumentException("Not support resource!")
                }
            }
            options.error?.let {
                val resId = it.drawableId
                val drawable = it.drawable
                when {
                    drawable != null -> error(it.drawable)
                    resId != null -> error(resId)
                    else -> throw IllegalArgumentException("Not support resource!")
                }
            }
            diskCacheStrategy(DiskCacheStrategy.DATA)
            if (!options.showAni) {
                dontAnimate()
            }
            options.signature?.let { this.signature(ObjectKey(it)) }
            if (options.refresh) {
                skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
            }
            if (options.transforms.isNotEmpty()) {
                options.transforms.let {
                    if (it.size == 1) {
                        this.transform(it[0])
                    } else {
                        this.transforms(*(options.transforms.toTypedArray()))
                    }
                }
            }
        }
        req.apply(reqOptions)
                .apply {
                    for (listener in options.requestListeners) {
                        this.addListener(listener)
                    }
                }
                .into(imageView)
    }


}